90b382a744be02b8b91befee23e4b71499dcaf39
3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 # Clear these on every parse, bug 4549
156 $this->mTemplates
= array();
157 $this->mTemplatePath
= array();
159 wfRunHooks( 'ParserClearState', array( &$this ) );
163 * Accessor for mUniqPrefix.
167 function UniqPrefix() {
168 return $this->mUniqPrefix
;
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
198 $this->mOptions
= $options;
199 $this->mTitle
=& $title;
200 $this->mRevisionId
= $revid;
201 $this->mOutputType
= OT_HTML
;
203 $this->mStripState
= NULL;
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState
;
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
219 $text = $this->internalParse( $text );
221 $text = $this->unstrip( $text, $this->mStripState
);
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1 ',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
235 $text = $this->doBlockLevels( $text, $linestart );
237 $this->replaceLinkHolders( $text );
239 # the position of the parserConvert() call should not be changed. it
240 # assumes that the links are all replaced and the only thing left
241 # is the <nowiki> mark.
242 # Side-effects: this calls $this->mOutput->setTitleText()
243 $text = $wgContLang->parserConvert( $text, $this );
245 $text = $this->unstripNoWiki( $text, $this->mStripState
);
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
249 $text = Sanitizer
::normalizeCharReferences( $text );
251 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
252 $text = Parser
::tidy($text);
255 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
257 $this->mOutput
->setText( $text );
258 wfProfileOut( $fname );
260 return $this->mOutput
;
264 * Get a random string
269 function getRandomString() {
270 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
273 function &getTitle() { return $this->mTitle
; }
274 function getOptions() { return $this->mOptions
; }
277 * Replaces all occurrences of <$tag>content</$tag> in the text
278 * with a random marker and returns the new text. the output parameter
279 * $content will be an associative array filled with data on the form
280 * $unique_marker => content.
282 * If $content is already set, the additional entries will be appended
283 * If $tag is set to STRIP_COMMENTS, the function will extract
284 * <!-- HTML comments -->
289 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
290 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
305 if( $tag == STRIP_COMMENTS
) {
306 $start = '/<!--()()/';
309 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
310 $end = "/<\\/$tag\\s*>/i";
313 while ( '' != $text ) {
314 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
316 if( count( $p ) < 4 ) {
323 $marker = $rnd . sprintf('%08X', $n++
);
324 $stripped .= $marker;
326 $tags[$marker] = "<$tag$attributes$empty>";
327 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
329 if ( $empty === '/' ) {
330 // Empty element tag, <tag />
331 $content[$marker] = null;
334 $q = preg_split( $end, $inside, 2 );
335 $content[$marker] = $q[0];
336 if( count( $q ) < 2 ) {
337 # No end tag -- let it run out to the end of the text.
348 * Wrapper function for extractTagsAndParams
349 * for cases where $tags and $params isn't needed
350 * i.e. where tags will never have params, like <nowiki>
355 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
356 $dummy_tags = array();
357 $dummy_params = array();
359 return Parser
::extractTagsAndParams( $tag, $text, $content,
360 $dummy_tags, $dummy_params, $uniq_prefix );
364 * Strips and renders nowiki, pre, math, hiero
365 * If $render is set, performs necessary rendering operations on plugins
366 * Returns the text, and fills an array with data needed in unstrip()
367 * If the $state is already a valid strip state, it adds to the state
369 * @param bool $stripcomments when set, HTML comments <!-- like this -->
370 * will be stripped in addition to other tags. This is important
371 * for section editing, where these comments cause confusion when
372 * counting the sections in the wikisource
376 function strip( $text, &$state, $stripcomments = false ) {
377 $render = ($this->mOutputType
== OT_HTML
);
378 $html_content = array();
379 $nowiki_content = array();
380 $math_content = array();
381 $pre_content = array();
382 $comment_content = array();
383 $ext_content = array();
385 $ext_params = array();
386 $gallery_content = array();
388 # Replace any instances of the placeholders
389 $uniq_prefix = $this->mUniqPrefix
;
390 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
395 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
396 foreach( $html_content as $marker => $content ) {
398 # Raw and unchecked for validity.
399 $html_content[$marker] = $content;
401 $html_content[$marker] = '<html>'.$content.'</html>';
407 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
408 foreach( $nowiki_content as $marker => $content ) {
410 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
412 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
417 if( $this->mOptions
->getUseTeX() ) {
418 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
419 foreach( $math_content as $marker => $content ){
421 $math_content[$marker] = renderMath( $content );
423 $math_content[$marker] = '<math>'.$content.'</math>';
429 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
430 foreach( $pre_content as $marker => $content ){
432 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
434 $pre_content[$marker] = '<pre>'.$content.'</pre>';
439 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
440 foreach( $gallery_content as $marker => $content ) {
441 require_once( 'ImageGallery.php' );
443 $gallery_content[$marker] = $this->renderImageGallery( $content );
445 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
451 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
452 foreach( $comment_content as $marker => $content ){
453 $comment_content[$marker] = '<!--'.$content.'-->';
458 foreach ( $this->mTagHooks
as $tag => $callback ) {
459 $ext_content[$tag] = array();
460 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
461 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
462 foreach( $ext_content[$tag] as $marker => $content ) {
463 $full_tag = $ext_tags[$tag][$marker];
464 $params = $ext_params[$tag][$marker];
466 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
468 if ( is_null( $content ) ) {
470 $ext_content[$tag][$marker] = $full_tag;
472 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
478 # Merge state with the pre-existing state, if there is one
480 $state['html'] = $state['html'] +
$html_content;
481 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
482 $state['math'] = $state['math'] +
$math_content;
483 $state['pre'] = $state['pre'] +
$pre_content;
484 $state['gallery'] = $state['gallery'] +
$gallery_content;
485 $state['comment'] = $state['comment'] +
$comment_content;
487 foreach( $ext_content as $tag => $array ) {
488 if ( array_key_exists( $tag, $state ) ) {
489 $state[$tag] = $state[$tag] +
$array;
494 'html' => $html_content,
495 'nowiki' => $nowiki_content,
496 'math' => $math_content,
497 'pre' => $pre_content,
498 'gallery' => $gallery_content,
499 'comment' => $comment_content,
506 * restores pre, math, and hiero removed by strip()
508 * always call unstripNoWiki() after this one
511 function unstrip( $text, &$state ) {
512 if ( !is_array( $state ) ) {
516 # Must expand in reverse order, otherwise nested tags will be corrupted
517 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
518 if( $tag != 'nowiki' && $tag != 'html' ) {
519 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
520 $text = str_replace( $uniq, $content, $text );
529 * always call this after unstrip() to preserve the order
533 function unstripNoWiki( $text, &$state ) {
534 if ( !is_array( $state ) ) {
538 # Must expand in reverse order, otherwise nested tags will be corrupted
539 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
540 $text = str_replace( key( $state['nowiki'] ), $content, $text );
545 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
546 $text = str_replace( key( $state['html'] ), $content, $text );
554 * Add an item to the strip state
555 * Returns the unique tag which must be inserted into the stripped text
556 * The tag will be replaced with the original text in unstrip()
560 function insertStripItem( $text, &$state ) {
561 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
568 'comment' => array(),
569 'gallery' => array(),
572 $state['item'][$rnd] = $text;
577 * Interface with html tidy, used if $wgUseTidy = true.
578 * If tidy isn't able to correct the markup, the original will be
579 * returned in all its glory with a warning comment appended.
581 * Either the external tidy program or the in-process tidy extension
582 * will be used depending on availability. Override the default
583 * $wgTidyInternal setting to disable the internal if it's not working.
585 * @param string $text Hideous HTML input
586 * @return string Corrected HTML output
590 function tidy( $text ) {
591 global $wgTidyInternal;
592 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
593 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
594 '<head><title>test</title></head><body>'.$text.'</body></html>';
595 if( $wgTidyInternal ) {
596 $correctedtext = Parser
::internalTidy( $wrappedtext );
598 $correctedtext = Parser
::externalTidy( $wrappedtext );
600 if( is_null( $correctedtext ) ) {
601 wfDebug( "Tidy error detected!\n" );
602 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
604 return $correctedtext;
608 * Spawn an external HTML tidy process and get corrected markup back from it.
613 function externalTidy( $text ) {
614 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
615 $fname = 'Parser::externalTidy';
616 wfProfileIn( $fname );
621 $descriptorspec = array(
622 0 => array('pipe', 'r'),
623 1 => array('pipe', 'w'),
624 2 => array('file', '/dev/null', 'a')
627 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
628 if (is_resource($process)) {
629 // Theoretically, this style of communication could cause a deadlock
630 // here. If the stdout buffer fills up, then writes to stdin could
631 // block. This doesn't appear to happen with tidy, because tidy only
632 // writes to stdout after it's finished reading from stdin. Search
633 // for tidyParseStdin and tidySaveStdout in console/tidy.c
634 fwrite($pipes[0], $text);
636 while (!feof($pipes[1])) {
637 $cleansource .= fgets($pipes[1], 1024);
640 proc_close($process);
643 wfProfileOut( $fname );
645 if( $cleansource == '' && $text != '') {
646 // Some kind of error happened, so we couldn't get the corrected text.
647 // Just give up; we'll use the source text and append a warning.
655 * Use the HTML tidy PECL extension to use the tidy library in-process,
656 * saving the overhead of spawning a new process. Currently written to
657 * the PHP 4.3.x version of the extension, may not work on PHP 5.
659 * 'pear install tidy' should be able to compile the extension module.
664 function internalTidy( $text ) {
666 $fname = 'Parser::internalTidy';
667 wfProfileIn( $fname );
669 tidy_load_config( $wgTidyConf );
670 tidy_set_encoding( 'utf8' );
671 tidy_parse_string( $text );
673 if( tidy_get_status() == 2 ) {
674 // 2 is magic number for fatal error
675 // http://www.php.net/manual/en/function.tidy-get-status.php
678 $cleansource = tidy_get_output();
680 wfProfileOut( $fname );
685 * parse the wiki syntax used to render tables
689 function doTableStuff ( $t ) {
690 $fname = 'Parser::doTableStuff';
691 wfProfileIn( $fname );
693 $t = explode ( "\n" , $t ) ;
694 $td = array () ; # Is currently a td tag open?
695 $ltd = array () ; # Was it TD or TH?
696 $tr = array () ; # Is currently a tr tag open?
697 $ltr = array () ; # tr attributes
698 $has_opened_tr = array(); # Did this table open a <tr> element?
699 $indent_level = 0; # indent level of the table
700 foreach ( $t AS $k => $x )
703 $fc = substr ( $x , 0 , 1 ) ;
704 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
705 $indent_level = strlen( $matches[1] );
707 $attributes = $this->unstripForHTML( $matches[2] );
709 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
710 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
711 array_push ( $td , false ) ;
712 array_push ( $ltd , '' ) ;
713 array_push ( $tr , false ) ;
714 array_push ( $ltr , '' ) ;
715 array_push ( $has_opened_tr, false );
717 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
718 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
719 $z = "</table>" . substr ( $x , 2);
720 $l = array_pop ( $ltd ) ;
721 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
722 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
723 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
725 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
727 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
728 $x = substr ( $x , 1 ) ;
729 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
731 $l = array_pop ( $ltd ) ;
732 array_pop ( $has_opened_tr );
733 array_push ( $has_opened_tr , true ) ;
734 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
735 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
738 array_push ( $tr , false ) ;
739 array_push ( $td , false ) ;
740 array_push ( $ltd , '' ) ;
741 $attributes = $this->unstripForHTML( $x );
742 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
744 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
746 if ( '|+' == substr ( $x , 0 , 2 ) ) {
748 $x = substr ( $x , 1 ) ;
750 $after = substr ( $x , 1 ) ;
751 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
752 $after = explode ( '||' , $after ) ;
755 # Loop through each table cell
756 foreach ( $after AS $theline )
761 $tra = array_pop ( $ltr ) ;
762 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
763 array_push ( $tr , true ) ;
764 array_push ( $ltr , '' ) ;
765 array_pop ( $has_opened_tr );
766 array_push ( $has_opened_tr , true ) ;
769 $l = array_pop ( $ltd ) ;
770 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
771 if ( $fc == '|' ) $l = 'td' ;
772 else if ( $fc == '!' ) $l = 'th' ;
773 else if ( $fc == '+' ) $l = 'caption' ;
775 array_push ( $ltd , $l ) ;
778 $y = explode ( '|' , $theline , 2 ) ;
779 # Note that a '|' inside an invalid link should not
780 # be mistaken as delimiting cell parameters
781 if ( strpos( $y[0], '[[' ) !== false ) {
782 $y = array ($theline);
784 if ( count ( $y ) == 1 )
785 $y = "{$z}<{$l}>{$y[0]}" ;
787 $attributes = $this->unstripForHTML( $y[0] );
788 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
791 array_push ( $td , true ) ;
796 # Closing open td, tr && table
797 while ( count ( $td ) > 0 )
799 $l = array_pop ( $ltd ) ;
800 if ( array_pop ( $td ) ) $t[] = '</td>' ;
801 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
802 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
806 $t = implode ( "\n" , $t ) ;
807 wfProfileOut( $fname );
812 * Helper function for parse() that transforms wiki markup into
813 * HTML. Only called for $mOutputType == OT_HTML.
817 function internalParse( $text ) {
821 $fname = 'Parser::internalParse';
822 wfProfileIn( $fname );
824 # Remove <noinclude> tags and <includeonly> sections
825 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
826 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
827 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
829 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
830 $text = $this->replaceVariables( $text, $args );
832 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
834 $text = $this->doHeadings( $text );
835 if($this->mOptions
->getUseDynamicDates()) {
836 $df =& DateFormatter
::getInstance();
837 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
839 $text = $this->doAllQuotes( $text );
840 $text = $this->replaceInternalLinks( $text );
841 $text = $this->replaceExternalLinks( $text );
843 # replaceInternalLinks may sometimes leave behind
844 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
845 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
847 $text = $this->doMagicLinks( $text );
848 $text = $this->doTableStuff( $text );
849 $text = $this->formatHeadings( $text, $isMain );
851 wfProfileOut( $fname );
856 * Replace special strings like "ISBN xxx" and "RFC xxx" with
857 * magic external links.
861 function &doMagicLinks( &$text ) {
862 $text = $this->magicISBN( $text );
863 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
864 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
869 * Parse headers and return html
873 function doHeadings( $text ) {
874 $fname = 'Parser::doHeadings';
875 wfProfileIn( $fname );
876 for ( $i = 6; $i >= 1; --$i ) {
877 $h = str_repeat( '=', $i );
878 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
879 "<h{$i}>\\1</h{$i}>\\2", $text );
881 wfProfileOut( $fname );
886 * Replace single quotes with HTML markup
888 * @return string the altered text
890 function doAllQuotes( $text ) {
891 $fname = 'Parser::doAllQuotes';
892 wfProfileIn( $fname );
894 $lines = explode( "\n", $text );
895 foreach ( $lines as $line ) {
896 $outtext .= $this->doQuotes ( $line ) . "\n";
898 $outtext = substr($outtext, 0,-1);
899 wfProfileOut( $fname );
904 * Helper function for doAllQuotes()
907 function doQuotes( $text ) {
908 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
909 if ( count( $arr ) == 1 )
913 # First, do some preliminary work. This may shift some apostrophes from
914 # being mark-up to being text. It also counts the number of occurrences
915 # of bold and italics mark-ups.
919 foreach ( $arr as $r )
921 if ( ( $i %
2 ) == 1 )
923 # If there are ever four apostrophes, assume the first is supposed to
924 # be text, and the remaining three constitute mark-up for bold text.
925 if ( strlen( $arr[$i] ) == 4 )
930 # If there are more than 5 apostrophes in a row, assume they're all
931 # text except for the last 5.
932 else if ( strlen( $arr[$i] ) > 5 )
934 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
937 # Count the number of occurrences of bold and italics mark-ups.
938 # We are not counting sequences of five apostrophes.
939 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
940 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
941 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
946 # If there is an odd number of both bold and italics, it is likely
947 # that one of the bold ones was meant to be an apostrophe followed
948 # by italics. Which one we cannot know for certain, but it is more
949 # likely to be one that has a single-letter word before it.
950 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
953 $firstsingleletterword = -1;
954 $firstmultiletterword = -1;
956 foreach ( $arr as $r )
958 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
960 $x1 = substr ($arr[$i-1], -1);
961 $x2 = substr ($arr[$i-1], -2, 1);
963 if ($firstspace == -1) $firstspace = $i;
964 } else if ($x2 == ' ') {
965 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
967 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
973 # If there is a single-letter word, use it!
974 if ($firstsingleletterword > -1)
976 $arr [ $firstsingleletterword ] = "''";
977 $arr [ $firstsingleletterword-1 ] .= "'";
979 # If not, but there's a multi-letter word, use that one.
980 else if ($firstmultiletterword > -1)
982 $arr [ $firstmultiletterword ] = "''";
983 $arr [ $firstmultiletterword-1 ] .= "'";
985 # ... otherwise use the first one that has neither.
986 # (notice that it is possible for all three to be -1 if, for example,
987 # there is only one pentuple-apostrophe in the line)
988 else if ($firstspace > -1)
990 $arr [ $firstspace ] = "''";
991 $arr [ $firstspace-1 ] .= "'";
995 # Now let's actually convert our apostrophic mush to HTML!
1000 foreach ($arr as $r)
1004 if ($state == 'both')
1011 if (strlen ($r) == 2)
1014 { $output .= '</i>'; $state = ''; }
1015 else if ($state == 'bi')
1016 { $output .= '</i>'; $state = 'b'; }
1017 else if ($state == 'ib')
1018 { $output .= '</b></i><b>'; $state = 'b'; }
1019 else if ($state == 'both')
1020 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1021 else # $state can be 'b' or ''
1022 { $output .= '<i>'; $state .= 'i'; }
1024 else if (strlen ($r) == 3)
1027 { $output .= '</b>'; $state = ''; }
1028 else if ($state == 'bi')
1029 { $output .= '</i></b><i>'; $state = 'i'; }
1030 else if ($state == 'ib')
1031 { $output .= '</b>'; $state = 'i'; }
1032 else if ($state == 'both')
1033 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1034 else # $state can be 'i' or ''
1035 { $output .= '<b>'; $state .= 'b'; }
1037 else if (strlen ($r) == 5)
1040 { $output .= '</b><i>'; $state = 'i'; }
1041 else if ($state == 'i')
1042 { $output .= '</i><b>'; $state = 'b'; }
1043 else if ($state == 'bi')
1044 { $output .= '</i></b>'; $state = ''; }
1045 else if ($state == 'ib')
1046 { $output .= '</b></i>'; $state = ''; }
1047 else if ($state == 'both')
1048 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1049 else # ($state == '')
1050 { $buffer = ''; $state = 'both'; }
1055 # Now close all remaining tags. Notice that the order is important.
1056 if ($state == 'b' ||
$state == 'ib')
1058 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1062 if ($state == 'both')
1063 $output .= '<b><i>'.$buffer.'</i></b>';
1069 * Replace external links
1071 * Note: this is all very hackish and the order of execution matters a lot.
1072 * Make sure to run maintenance/parserTests.php if you change this code.
1076 function replaceExternalLinks( $text ) {
1078 $fname = 'Parser::replaceExternalLinks';
1079 wfProfileIn( $fname );
1081 $sk =& $this->mOptions
->getSkin();
1083 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1085 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1088 while ( $i<count( $bits ) ) {
1090 $protocol = $bits[$i++
];
1091 $text = $bits[$i++
];
1092 $trail = $bits[$i++
];
1094 # The characters '<' and '>' (which were escaped by
1095 # removeHTMLtags()) should not be included in
1096 # URLs, per RFC 2396.
1097 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1098 $text = substr($url, $m2[0][1]) . ' ' . $text;
1099 $url = substr($url, 0, $m2[0][1]);
1102 # If the link text is an image URL, replace it with an <img> tag
1103 # This happened by accident in the original parser, but some people used it extensively
1104 $img = $this->maybeMakeExternalImage( $text );
1105 if ( $img !== false ) {
1111 # Set linktype for CSS - if URL==text, link is essentially free
1112 $linktype = ($text == $url) ?
'free' : 'text';
1114 # No link text, e.g. [http://domain.tld/some.link]
1115 if ( $text == '' ) {
1116 # Autonumber if allowed
1117 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1118 $text = '[' . ++
$this->mAutonumber
. ']';
1119 $linktype = 'autonumber';
1121 # Otherwise just use the URL
1122 $text = htmlspecialchars( $url );
1126 # Have link text, e.g. [http://domain.tld/some.link text]s
1128 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1131 $text = $wgContLang->markNoConversion($text);
1133 # Replace & from obsolete syntax with &.
1134 # All HTML entities will be escaped by makeExternalLink()
1135 $url = str_replace( '&', '&', $url );
1136 # Replace unnecessary URL escape codes with the referenced character
1137 # This prevents spammers from hiding links from the filters
1138 $url = Parser
::replaceUnusualEscapes( $url );
1140 # Process the trail (i.e. everything after this link up until start of the next link),
1141 # replacing any non-bracketed links
1142 $trail = $this->replaceFreeExternalLinks( $trail );
1144 # Use the encoded URL
1145 # This means that users can paste URLs directly into the text
1146 # Funny characters like ö aren't valid in URLs anyway
1147 # This was changed in August 2004
1148 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1150 # Register link in the output object
1151 $this->mOutput
->addExternalLink( $url );
1154 wfProfileOut( $fname );
1159 * Replace anything that looks like a URL with a link
1162 function replaceFreeExternalLinks( $text ) {
1164 $fname = 'Parser::replaceFreeExternalLinks';
1165 wfProfileIn( $fname );
1167 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1168 $s = array_shift( $bits );
1171 $sk =& $this->mOptions
->getSkin();
1173 while ( $i < count( $bits ) ){
1174 $protocol = $bits[$i++
];
1175 $remainder = $bits[$i++
];
1177 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1178 # Found some characters after the protocol that look promising
1179 $url = $protocol . $m[1];
1182 # The characters '<' and '>' (which were escaped by
1183 # removeHTMLtags()) should not be included in
1184 # URLs, per RFC 2396.
1185 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1186 $trail = substr($url, $m2[0][1]) . $trail;
1187 $url = substr($url, 0, $m2[0][1]);
1190 # Move trailing punctuation to $trail
1192 # If there is no left bracket, then consider right brackets fair game too
1193 if ( strpos( $url, '(' ) === false ) {
1197 $numSepChars = strspn( strrev( $url ), $sep );
1198 if ( $numSepChars ) {
1199 $trail = substr( $url, -$numSepChars ) . $trail;
1200 $url = substr( $url, 0, -$numSepChars );
1203 # Replace & from obsolete syntax with &.
1204 # All HTML entities will be escaped by makeExternalLink()
1205 # or maybeMakeExternalImage()
1206 $url = str_replace( '&', '&', $url );
1207 # Replace unnecessary URL escape codes with their equivalent characters
1208 $url = Parser
::replaceUnusualEscapes( $url );
1210 # Is this an external image?
1211 $text = $this->maybeMakeExternalImage( $url );
1212 if ( $text === false ) {
1213 # Not an image, make a link
1214 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1215 # Register it in the output object
1216 $this->mOutput
->addExternalLink( $url );
1218 $s .= $text . $trail;
1220 $s .= $protocol . $remainder;
1223 wfProfileOut( $fname );
1228 * Replace unusual URL escape codes with their equivalent characters
1233 function replaceUnusualEscapes( $url ) {
1234 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1235 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1239 * Callback function used in replaceUnusualEscapes().
1240 * Replaces unusual URL escape codes with their equivalent character
1244 function replaceUnusualEscapesCallback( $matches ) {
1245 $char = urldecode( $matches[0] );
1246 $ord = ord( $char );
1247 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1248 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1249 // No, shouldn't be escaped
1252 // Yes, leave it escaped
1258 * make an image if it's allowed, either through the global
1259 * option or through the exception
1262 function maybeMakeExternalImage( $url ) {
1263 $sk =& $this->mOptions
->getSkin();
1264 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1265 $imagesexception = !empty($imagesfrom);
1267 if ( $this->mOptions
->getAllowExternalImages()
1268 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1269 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1271 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1278 * Process [[ ]] wikilinks
1282 function replaceInternalLinks( $s ) {
1284 static $fname = 'Parser::replaceInternalLinks' ;
1286 wfProfileIn( $fname );
1288 wfProfileIn( $fname.'-setup' );
1290 # the % is needed to support urlencoded titles as well
1291 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1293 $sk =& $this->mOptions
->getSkin();
1295 #split the entire text string on occurences of [[
1296 $a = explode( '[[', ' ' . $s );
1297 #get the first element (all text up to first [[), and remove the space we added
1298 $s = array_shift( $a );
1299 $s = substr( $s, 1 );
1301 # Match a link having the form [[namespace:link|alternate]]trail
1303 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1304 # Match cases where there is no "]]", which might still be images
1305 static $e1_img = FALSE;
1306 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1307 # Match the end of a line for a word that's not followed by whitespace,
1308 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1309 $e2 = wfMsgForContent( 'linkprefix' );
1311 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1313 if( is_null( $this->mTitle
) ) {
1314 wfDebugDieBacktrace( 'nooo' );
1316 $nottalk = !$this->mTitle
->isTalkPage();
1318 if ( $useLinkPrefixExtension ) {
1319 if ( preg_match( $e2, $s, $m ) ) {
1320 $first_prefix = $m[2];
1322 $first_prefix = false;
1328 $selflink = $this->mTitle
->getPrefixedText();
1329 wfProfileOut( $fname.'-setup' );
1331 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1332 $useSubpages = $this->areSubpagesAllowed();
1334 # Loop for each link
1335 for ($k = 0; isset( $a[$k] ); $k++
) {
1337 if ( $useLinkPrefixExtension ) {
1338 wfProfileIn( $fname.'-prefixhandling' );
1339 if ( preg_match( $e2, $s, $m ) ) {
1347 $prefix = $first_prefix;
1348 $first_prefix = false;
1350 wfProfileOut( $fname.'-prefixhandling' );
1353 $might_be_img = false;
1355 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1357 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1358 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1359 # the real problem is with the $e1 regex
1362 # Still some problems for cases where the ] is meant to be outside punctuation,
1363 # and no image is in sight. See bug 2095.
1365 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1366 $text .= ']'; # so that replaceExternalLinks($text) works later
1369 # fix up urlencoded title texts
1370 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1372 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1373 $might_be_img = true;
1375 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1377 } else { # Invalid form; output directly
1378 $s .= $prefix . '[[' . $line ;
1382 # Don't allow internal links to pages containing
1383 # PROTO: where PROTO is a valid URL protocol; these
1384 # should be external links.
1385 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1386 $s .= $prefix . '[[' . $line ;
1390 # Make subpage if necessary
1391 if( $useSubpages ) {
1392 $link = $this->maybeDoSubpageLink( $m[1], $text );
1397 $noforce = (substr($m[1], 0, 1) != ':');
1399 # Strip off leading ':'
1400 $link = substr($link, 1);
1403 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1405 $s .= $prefix . '[[' . $line;
1409 #check other language variants of the link
1410 #if the article does not exist
1411 if( $checkVariantLink
1412 && $nt->getArticleID() == 0 ) {
1413 $wgContLang->findVariantLink($link, $nt);
1416 $ns = $nt->getNamespace();
1417 $iw = $nt->getInterWiki();
1419 if ($might_be_img) { # if this is actually an invalid link
1420 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1422 while (isset ($a[$k+
1]) ) {
1423 #look at the next 'line' to see if we can close it there
1424 $spliced = array_splice( $a, $k +
1, 1 );
1425 $next_line = array_shift( $spliced );
1426 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1427 # the first ]] closes the inner link, the second the image
1429 $text .= '[[' . $m[1];
1432 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1433 #if there's exactly one ]] that's fine, we'll keep looking
1434 $text .= '[[' . $m[0];
1436 #if $next_line is invalid too, we need look no further
1437 $text .= '[[' . $next_line;
1442 # we couldn't find the end of this imageLink, so output it raw
1443 #but don't ignore what might be perfectly normal links in the text we've examined
1444 $text = $this->replaceInternalLinks($text);
1445 $s .= $prefix . '[[' . $link . '|' . $text;
1446 # note: no $trail, because without an end, there *is* no trail
1449 } else { #it's not an image, so output it raw
1450 $s .= $prefix . '[[' . $link . '|' . $text;
1451 # note: no $trail, because without an end, there *is* no trail
1456 $wasblank = ( '' == $text );
1457 if( $wasblank ) $text = $link;
1460 # Link not escaped by : , create the various objects
1464 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1465 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1466 $s = rtrim($s . "\n");
1467 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1471 if ( $ns == NS_IMAGE
) {
1472 wfProfileIn( "$fname-image" );
1473 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1474 # recursively parse links inside the image caption
1475 # actually, this will parse them in any other parameters, too,
1476 # but it might be hard to fix that, and it doesn't matter ATM
1477 $text = $this->replaceExternalLinks($text);
1478 $text = $this->replaceInternalLinks($text);
1480 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1481 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1482 $this->mOutput
->addImage( $nt->getDBkey() );
1484 wfProfileOut( "$fname-image" );
1487 wfProfileOut( "$fname-image" );
1491 if ( $ns == NS_CATEGORY
) {
1492 wfProfileIn( "$fname-category" );
1493 $s = rtrim($s . "\n"); # bug 87
1496 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1497 $sortkey = $this->mTitle
->getText();
1499 $sortkey = $this->mTitle
->getPrefixedText();
1504 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1505 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1506 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1509 * Strip the whitespace Category links produce, see bug 87
1510 * @todo We might want to use trim($tmp, "\n") here.
1512 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1514 wfProfileOut( "$fname-category" );
1519 if( ( $nt->getPrefixedText() === $selflink ) &&
1520 ( $nt->getFragment() === '' ) ) {
1521 # Self-links are handled specially; generally de-link and change to bold.
1522 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1526 # Special and Media are pseudo-namespaces; no pages actually exist in them
1527 if( $ns == NS_MEDIA
) {
1528 $link = $sk->makeMediaLinkObj( $nt, $text );
1529 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1530 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1531 $this->mOutput
->addImage( $nt->getDBkey() );
1533 } elseif( $ns == NS_SPECIAL
) {
1534 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1536 } elseif( $ns == NS_IMAGE
) {
1537 $img = Image
::newFromTitle( $nt );
1538 if( $img->exists() ) {
1539 // Force a blue link if the file exists; may be a remote
1540 // upload on the shared repository, and we want to see its
1541 // auto-generated page.
1542 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1546 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1548 wfProfileOut( $fname );
1553 * Make a link placeholder. The text returned can be later resolved to a real link with
1554 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1555 * parsing of interwiki links, and secondly to allow all extistence checks and
1556 * article length checks (for stub links) to be bundled into a single query.
1559 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1560 if ( ! is_object($nt) ) {
1562 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1564 # Separate the link trail from the rest of the link
1565 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1567 if ( $nt->isExternal() ) {
1568 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1569 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1570 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1572 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1573 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1574 $this->mLinkHolders
['queries'][] = $query;
1575 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1576 $this->mLinkHolders
['titles'][] = $nt;
1578 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1585 * Render a forced-blue link inline; protect against double expansion of
1586 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1587 * Since this little disaster has to split off the trail text to avoid
1588 * breaking URLs in the following text without breaking trails on the
1589 * wiki links, it's been made into a horrible function.
1592 * @param string $text
1593 * @param string $query
1594 * @param string $trail
1595 * @param string $prefix
1596 * @return string HTML-wikitext mix oh yuck
1598 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1599 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1600 $sk =& $this->mOptions
->getSkin();
1601 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1602 return $this->armorLinks( $link ) . $trail;
1606 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1607 * going to go through further parsing steps before inline URL expansion.
1609 * In particular this is important when using action=render, which causes
1610 * full URLs to be included.
1612 * Oh man I hate our multi-layer parser!
1614 * @param string more-or-less HTML
1615 * @return string less-or-more HTML with NOPARSE bits
1617 function armorLinks( $text ) {
1618 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1619 "{$this->mUniqPrefix}NOPARSE$1", $text );
1623 * Return true if subpage links should be expanded on this page.
1626 function areSubpagesAllowed() {
1627 # Some namespaces don't allow subpages
1628 global $wgNamespacesWithSubpages;
1629 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1633 * Handle link to subpage if necessary
1634 * @param string $target the source of the link
1635 * @param string &$text the link text, modified as necessary
1636 * @return string the full name of the link
1639 function maybeDoSubpageLink($target, &$text) {
1642 # :Foobar -- override special treatment of prefix (images, language links)
1643 # /Foobar -- convert to CurrentPage/Foobar
1644 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1645 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1646 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1648 $fname = 'Parser::maybeDoSubpageLink';
1649 wfProfileIn( $fname );
1650 $ret = $target; # default return value is no change
1652 # Some namespaces don't allow subpages,
1653 # so only perform processing if subpages are allowed
1654 if( $this->areSubpagesAllowed() ) {
1655 # Look at the first character
1656 if( $target != '' && $target{0} == '/' ) {
1657 # / at end means we don't want the slash to be shown
1658 if( substr( $target, -1, 1 ) == '/' ) {
1659 $target = substr( $target, 1, -1 );
1662 $noslash = substr( $target, 1 );
1665 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1666 if( '' === $text ) {
1668 } # this might be changed for ugliness reasons
1670 # check for .. subpage backlinks
1672 $nodotdot = $target;
1673 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1675 $nodotdot = substr( $nodotdot, 3 );
1677 if($dotdotcount > 0) {
1678 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1679 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1680 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1681 # / at the end means don't show full path
1682 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1683 $nodotdot = substr( $nodotdot, 0, -1 );
1684 if( '' === $text ) {
1688 $nodotdot = trim( $nodotdot );
1689 if( $nodotdot != '' ) {
1690 $ret .= '/' . $nodotdot;
1697 wfProfileOut( $fname );
1702 * Used by doBlockLevels()
1705 /* private */ function closeParagraph() {
1707 if ( '' != $this->mLastSection
) {
1708 $result = '</' . $this->mLastSection
. ">\n";
1710 $this->mInPre
= false;
1711 $this->mLastSection
= '';
1714 # getCommon() returns the length of the longest common substring
1715 # of both arguments, starting at the beginning of both.
1717 /* private */ function getCommon( $st1, $st2 ) {
1718 $fl = strlen( $st1 );
1719 $shorter = strlen( $st2 );
1720 if ( $fl < $shorter ) { $shorter = $fl; }
1722 for ( $i = 0; $i < $shorter; ++
$i ) {
1723 if ( $st1{$i} != $st2{$i} ) { break; }
1727 # These next three functions open, continue, and close the list
1728 # element appropriate to the prefix character passed into them.
1730 /* private */ function openList( $char ) {
1731 $result = $this->closeParagraph();
1733 if ( '*' == $char ) { $result .= '<ul><li>'; }
1734 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1735 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1736 else if ( ';' == $char ) {
1737 $result .= '<dl><dt>';
1738 $this->mDTopen
= true;
1740 else { $result = '<!-- ERR 1 -->'; }
1745 /* private */ function nextItem( $char ) {
1746 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1747 else if ( ':' == $char ||
';' == $char ) {
1749 if ( $this->mDTopen
) { $close = '</dt>'; }
1750 if ( ';' == $char ) {
1751 $this->mDTopen
= true;
1752 return $close . '<dt>';
1754 $this->mDTopen
= false;
1755 return $close . '<dd>';
1758 return '<!-- ERR 2 -->';
1761 /* private */ function closeList( $char ) {
1762 if ( '*' == $char ) { $text = '</li></ul>'; }
1763 else if ( '#' == $char ) { $text = '</li></ol>'; }
1764 else if ( ':' == $char ) {
1765 if ( $this->mDTopen
) {
1766 $this->mDTopen
= false;
1767 $text = '</dt></dl>';
1769 $text = '</dd></dl>';
1772 else { return '<!-- ERR 3 -->'; }
1778 * Make lists from lines starting with ':', '*', '#', etc.
1781 * @return string the lists rendered as HTML
1783 function doBlockLevels( $text, $linestart ) {
1784 $fname = 'Parser::doBlockLevels';
1785 wfProfileIn( $fname );
1787 # Parsing through the text line by line. The main thing
1788 # happening here is handling of block-level elements p, pre,
1789 # and making lists from lines starting with * # : etc.
1791 $textLines = explode( "\n", $text );
1793 $lastPrefix = $output = '';
1794 $this->mDTopen
= $inBlockElem = false;
1796 $paragraphStack = false;
1798 if ( !$linestart ) {
1799 $output .= array_shift( $textLines );
1801 foreach ( $textLines as $oLine ) {
1802 $lastPrefixLength = strlen( $lastPrefix );
1803 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1804 $preOpenMatch = preg_match('/<pre/i', $oLine );
1805 if ( !$this->mInPre
) {
1806 # Multiple prefixes may abut each other for nested lists.
1807 $prefixLength = strspn( $oLine, '*#:;' );
1808 $pref = substr( $oLine, 0, $prefixLength );
1811 $pref2 = str_replace( ';', ':', $pref );
1812 $t = substr( $oLine, $prefixLength );
1813 $this->mInPre
= !empty($preOpenMatch);
1815 # Don't interpret any other prefixes in preformatted text
1817 $pref = $pref2 = '';
1822 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1823 # Same as the last item, so no need to deal with nesting or opening stuff
1824 $output .= $this->nextItem( substr( $pref, -1 ) );
1825 $paragraphStack = false;
1827 if ( substr( $pref, -1 ) == ';') {
1828 # The one nasty exception: definition lists work like this:
1829 # ; title : definition text
1830 # So we check for : in the remainder text to split up the
1831 # title and definition, without b0rking links.
1833 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1835 $output .= $term . $this->nextItem( ':' );
1838 } elseif( $prefixLength ||
$lastPrefixLength ) {
1839 # Either open or close a level...
1840 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1841 $paragraphStack = false;
1843 while( $commonPrefixLength < $lastPrefixLength ) {
1844 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1845 --$lastPrefixLength;
1847 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1848 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1850 while ( $prefixLength > $commonPrefixLength ) {
1851 $char = substr( $pref, $commonPrefixLength, 1 );
1852 $output .= $this->openList( $char );
1854 if ( ';' == $char ) {
1855 # FIXME: This is dupe of code above
1856 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1858 $output .= $term . $this->nextItem( ':' );
1861 ++
$commonPrefixLength;
1863 $lastPrefix = $pref2;
1865 if( 0 == $prefixLength ) {
1866 wfProfileIn( "$fname-paragraph" );
1867 # No prefix (not in list)--go to paragraph mode
1868 // XXX: use a stack for nestable elements like span, table and div
1869 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1870 $closematch = preg_match(
1871 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1872 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1873 if ( $openmatch or $closematch ) {
1874 $paragraphStack = false;
1875 $output .= $this->closeParagraph();
1876 if ( $preOpenMatch and !$preCloseMatch ) {
1877 $this->mInPre
= true;
1879 if ( $closematch ) {
1880 $inBlockElem = false;
1882 $inBlockElem = true;
1884 } else if ( !$inBlockElem && !$this->mInPre
) {
1885 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1887 if ($this->mLastSection
!= 'pre') {
1888 $paragraphStack = false;
1889 $output .= $this->closeParagraph().'<pre>';
1890 $this->mLastSection
= 'pre';
1892 $t = substr( $t, 1 );
1895 if ( '' == trim($t) ) {
1896 if ( $paragraphStack ) {
1897 $output .= $paragraphStack.'<br />';
1898 $paragraphStack = false;
1899 $this->mLastSection
= 'p';
1901 if ($this->mLastSection
!= 'p' ) {
1902 $output .= $this->closeParagraph();
1903 $this->mLastSection
= '';
1904 $paragraphStack = '<p>';
1906 $paragraphStack = '</p><p>';
1910 if ( $paragraphStack ) {
1911 $output .= $paragraphStack;
1912 $paragraphStack = false;
1913 $this->mLastSection
= 'p';
1914 } else if ($this->mLastSection
!= 'p') {
1915 $output .= $this->closeParagraph().'<p>';
1916 $this->mLastSection
= 'p';
1921 wfProfileOut( "$fname-paragraph" );
1923 // somewhere above we forget to get out of pre block (bug 785)
1924 if($preCloseMatch && $this->mInPre
) {
1925 $this->mInPre
= false;
1927 if ($paragraphStack === false) {
1931 while ( $prefixLength ) {
1932 $output .= $this->closeList( $pref2{$prefixLength-1} );
1935 if ( '' != $this->mLastSection
) {
1936 $output .= '</' . $this->mLastSection
. '>';
1937 $this->mLastSection
= '';
1940 wfProfileOut( $fname );
1945 * Split up a string on ':', ignoring any occurences inside
1946 * <a>..</a> or <span>...</span>
1947 * @param string $str the string to split
1948 * @param string &$before set to everything before the ':'
1949 * @param string &$after set to everything after the ':'
1950 * return string the position of the ':', or false if none found
1952 function findColonNoLinks($str, &$before, &$after) {
1953 # I wonder if we should make this count all tags, not just <a>
1954 # and <span>. That would prevent us from matching a ':' that
1955 # comes in the middle of italics other such formatting....
1957 $fname = 'Parser::findColonNoLinks';
1958 wfProfileIn( $fname );
1961 $colon = strpos($str, ':', $pos);
1963 if ($colon !== false) {
1964 $before = substr($str, 0, $colon);
1965 $after = substr($str, $colon +
1);
1967 # Skip any ':' within <a> or <span> pairs
1968 $a = substr_count($before, '<a');
1969 $s = substr_count($before, '<span');
1970 $ca = substr_count($before, '</a>');
1971 $cs = substr_count($before, '</span>');
1973 if ($a <= $ca and $s <= $cs) {
1974 # Tags are balanced before ':'; ok
1979 } while ($colon !== false);
1980 wfProfileOut( $fname );
1985 * Return value of a magic variable (like PAGENAME)
1989 function getVariableValue( $index ) {
1990 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1993 * Some of these require message or data lookups and can be
1994 * expensive to check many times.
1996 static $varCache = array();
1997 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1998 if ( isset( $varCache[$index] ) )
1999 return $varCache[$index];
2002 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2005 case MAG_CURRENTMONTH
:
2006 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2007 case MAG_CURRENTMONTHNAME
:
2008 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2009 case MAG_CURRENTMONTHNAMEGEN
:
2010 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2011 case MAG_CURRENTMONTHABBREV
:
2012 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2013 case MAG_CURRENTDAY
:
2014 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2015 case MAG_CURRENTDAY2
:
2016 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2018 return $this->mTitle
->getText();
2020 return $this->mTitle
->getPartialURL();
2021 case MAG_FULLPAGENAME
:
2022 return $this->mTitle
->getPrefixedText();
2023 case MAG_FULLPAGENAMEE
:
2024 return $this->mTitle
->getPrefixedURL();
2025 case MAG_REVISIONID
:
2026 return $this->mRevisionId
;
2028 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2029 case MAG_NAMESPACEE
:
2030 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2031 case MAG_CURRENTDAYNAME
:
2032 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2033 case MAG_CURRENTYEAR
:
2034 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2035 case MAG_CURRENTTIME
:
2036 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2037 case MAG_CURRENTWEEK
:
2038 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2039 // int to remove the padding
2040 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2041 case MAG_CURRENTDOW
:
2042 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2043 case MAG_NUMBEROFARTICLES
:
2044 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2045 case MAG_NUMBEROFFILES
:
2046 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2051 case MAG_SERVERNAME
:
2052 return $wgServerName;
2053 case MAG_SCRIPTPATH
:
2054 return $wgScriptPath;
2057 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2065 * initialise the magic variables (like CURRENTMONTHNAME)
2069 function initialiseVariables() {
2070 $fname = 'Parser::initialiseVariables';
2071 wfProfileIn( $fname );
2072 global $wgVariableIDs;
2073 $this->mVariables
= array();
2074 foreach ( $wgVariableIDs as $id ) {
2075 $mw =& MagicWord
::get( $id );
2076 $mw->addToArray( $this->mVariables
, $id );
2078 wfProfileOut( $fname );
2082 * parse any parentheses in format ((title|part|part))
2083 * and call callbacks to get a replacement text for any found piece
2085 * @param string $text The text to parse
2086 * @param array $callbacks rules in form:
2087 * '{' => array( # opening parentheses
2088 * 'end' => '}', # closing parentheses
2089 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2090 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2095 function replace_callback ($text, $callbacks) {
2096 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2097 $lastOpeningBrace = -1; # last not closed parentheses
2099 for ($i = 0; $i < strlen($text); $i++
) {
2100 # check for any opening brace
2103 foreach ($callbacks as $key => $value) {
2104 $pos = strpos ($text, $key, $i);
2105 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2111 if ($lastOpeningBrace >= 0) {
2112 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2114 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2119 $pos = strpos ($text, '|', $i);
2121 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2132 # found openning brace, lets add it to parentheses stack
2133 if (null != $rule) {
2134 $piece = array('brace' => $text[$i],
2135 'braceEnd' => $rule['end'],
2140 # count openning brace characters
2141 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2146 $piece['startAt'] = $i+
1;
2147 $piece['partStart'] = $i+
1;
2149 # we need to add to stack only if openning brace count is enough for any given rule
2150 foreach ($rule['cb'] as $cnt => $fn) {
2151 if ($piece['count'] >= $cnt) {
2152 $lastOpeningBrace ++
;
2153 $openingBraceStack[$lastOpeningBrace] = $piece;
2160 else if ($lastOpeningBrace >= 0) {
2161 # first check if it is a closing brace
2162 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2163 # lets check if it is enough characters for closing brace
2165 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2168 # if there are more closing parentheses than opening ones, we parse less
2169 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2170 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2172 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2174 $matchingCallback = null;
2175 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2176 if ($count >= $cnt && $matchingCount < $cnt) {
2177 $matchingCount = $cnt;
2178 $matchingCallback = $fn;
2182 if ($matchingCount == 0) {
2187 # lets set a title or last part (if '|' was found)
2188 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2189 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2191 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2193 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2194 $pieceEnd = $i +
$matchingCount;
2196 if( is_callable( $matchingCallback ) ) {
2198 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2199 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2200 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2201 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2203 # finally we can call a user callback and replace piece of text
2204 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2205 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2206 $i = $pieceStart +
strlen($replaceWith) - 1;
2209 # null value for callback means that parentheses should be parsed, but not replaced
2210 $i +
= $matchingCount - 1;
2213 # reset last openning parentheses, but keep it in case there are unused characters
2214 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2215 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2216 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2219 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2220 $openingBraceStack[$lastOpeningBrace--] = null;
2222 if ($matchingCount < $piece['count']) {
2223 $piece['count'] -= $matchingCount;
2224 $piece['startAt'] -= $matchingCount;
2225 $piece['partStart'] = $piece['startAt'];
2226 # do we still qualify for any callback with remaining count?
2227 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2228 if ($piece['count'] >= $cnt) {
2229 $lastOpeningBrace ++
;
2230 $openingBraceStack[$lastOpeningBrace] = $piece;
2238 # lets set a title if it is a first separator, or next part otherwise
2239 if ($text[$i] == '|') {
2240 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2241 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2242 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2245 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2247 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2256 * Replace magic variables, templates, and template arguments
2257 * with the appropriate text. Templates are substituted recursively,
2258 * taking care to avoid infinite loops.
2260 * Note that the substitution depends on value of $mOutputType:
2261 * OT_WIKI: only {{subst:}} templates
2262 * OT_MSG: only magic variables
2263 * OT_HTML: all templates and magic variables
2265 * @param string $tex The text to transform
2266 * @param array $args Key-value pairs representing template parameters to substitute
2267 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2270 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2271 # Prevent too big inclusions
2272 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2276 $fname = 'Parser::replaceVariables';
2277 wfProfileIn( $fname );
2279 # This function is called recursively. To keep track of arguments we need a stack:
2280 array_push( $this->mArgStack
, $args );
2282 $braceCallbacks = array();
2284 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2286 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2287 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2289 $callbacks = array();
2290 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2291 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2292 $text = $this->replace_callback ($text, $callbacks);
2294 array_pop( $this->mArgStack
);
2296 wfProfileOut( $fname );
2301 * Replace magic variables
2304 function variableSubstitution( $matches ) {
2305 $fname = 'Parser::variableSubstitution';
2306 $varname = $matches[1];
2307 wfProfileIn( $fname );
2308 if ( !$this->mVariables
) {
2309 $this->initialiseVariables();
2312 if ( $this->mOutputType
== OT_WIKI
) {
2313 # Do only magic variables prefixed by SUBST
2314 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2315 if (!$mwSubst->matchStartAndRemove( $varname ))
2317 # Note that if we don't substitute the variable below,
2318 # we don't remove the {{subst:}} magic word, in case
2319 # it is a template rather than a magic variable.
2321 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2322 $id = $this->mVariables
[$varname];
2323 $text = $this->getVariableValue( $id );
2324 $this->mOutput
->mContainsOldMagic
= true;
2326 $text = $matches[0];
2328 wfProfileOut( $fname );
2332 # Split template arguments
2333 function getTemplateArgs( $argsString ) {
2334 if ( $argsString === '' ) {
2338 $args = explode( '|', substr( $argsString, 1 ) );
2340 # If any of the arguments contains a '[[' but no ']]', it needs to be
2341 # merged with the next arg because the '|' character between belongs
2342 # to the link syntax and not the template parameter syntax.
2343 $argc = count($args);
2345 for ( $i = 0; $i < $argc-1; $i++
) {
2346 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2347 $args[$i] .= '|'.$args[$i+
1];
2348 array_splice($args, $i+
1, 1);
2358 * Return the text of a template, after recursively
2359 * replacing any variables or templates within the template.
2361 * @param array $piece The parts of the template
2362 * $piece['text']: matched text
2363 * $piece['title']: the title, i.e. the part before the |
2364 * $piece['parts']: the parameter array
2365 * @return string the text of the template
2368 function braceSubstitution( $piece ) {
2370 $fname = 'Parser::braceSubstitution';
2371 wfProfileIn( $fname );
2374 $found = false; # $text has been filled
2375 $nowiki = false; # wiki markup in $text should be escaped
2376 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2377 $noargs = false; # Don't replace triple-brace arguments in $text
2378 $replaceHeadings = false; # Make the edit section links go to the template not the article
2379 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2380 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2382 # Title object, where $text came from
2387 # $part1 is the bit before the first |, and must contain only title characters
2388 # $args is a list of arguments, starting from index 0, not including $part1
2390 $part1 = $piece['title'];
2391 # If the third subpattern matched anything, it will start with |
2393 if (null == $piece['parts']) {
2394 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2395 if ($replaceWith != $piece['text']) {
2396 $text = $replaceWith;
2403 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2404 $argc = count( $args );
2408 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2409 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2410 # One of two possibilities is true:
2411 # 1) Found SUBST but not in the PST phase
2412 # 2) Didn't find SUBST and in the PST phase
2413 # In either case, return without further processing
2414 $text = $piece['text'];
2421 # MSG, MSGNW, INT and RAW
2424 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2425 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2428 # Remove obsolete MSG:
2429 $mwMsg =& MagicWord
::get( MAG_MSG
);
2430 $mwMsg->matchStartAndRemove( $part1 );
2434 $mwRaw =& MagicWord
::get( MAG_RAW
);
2435 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2436 $forceRawInterwiki = true;
2439 # Check if it is an internal message
2440 $mwInt =& MagicWord
::get( MAG_INT
);
2441 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2442 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2443 $text = $linestart . wfMsgReal( $part1, $args, true );
2451 # Check for NS: (namespace expansion)
2452 $mwNs = MagicWord
::get( MAG_NS
);
2453 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2454 if ( intval( $part1 ) ||
$part1 == "0" ) {
2455 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2458 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2459 if ( !is_null( $index ) ) {
2460 $text = $linestart . $wgContLang->getNsText( $index );
2467 # LCFIRST, UCFIRST, LC and UC
2469 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2470 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2471 $lc =& MagicWord
::get( MAG_LC
);
2472 $uc =& MagicWord
::get( MAG_UC
);
2473 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2474 $text = $linestart . $wgContLang->lcfirst( $part1 );
2476 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2477 $text = $linestart . $wgContLang->ucfirst( $part1 );
2479 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2480 $text = $linestart . $wgContLang->lc( $part1 );
2482 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2483 $text = $linestart . $wgContLang->uc( $part1 );
2488 # LOCALURL and FULLURL
2490 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2491 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2492 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2493 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2496 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2497 $func = 'getLocalURL';
2498 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2499 $func = 'escapeLocalURL';
2500 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2501 $func = 'getFullURL';
2502 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2503 $func = 'escapeFullURL';
2508 if ( $func !== false ) {
2509 $title = Title
::newFromText( $part1 );
2510 if ( !is_null( $title ) ) {
2512 $text = $linestart . $title->$func( $args[0] );
2514 $text = $linestart . $title->$func();
2522 if ( !$found && $argc == 1 ) {
2523 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2524 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2525 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2531 if ( !$found && $argc >= 2 ) {
2532 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2533 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2534 if ($argc==2) {$args[2]=$args[1];}
2535 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2540 # Template table test
2542 # Did we encounter this template already? If yes, it is in the cache
2543 # and we need to check for loops.
2544 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2547 # Infinite loop test
2548 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2552 $text = $linestart .
2553 '{{' . $part1 . '}}' .
2554 '<!-- WARNING: template loop detected -->';
2555 wfDebug( "$fname: template loop broken at '$part1'\n" );
2557 # set $text to cached message.
2558 $text = $linestart . $this->mTemplates
[$piece['title']];
2562 # Load from database
2563 $lastPathLevel = $this->mTemplatePath
;
2566 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2567 if ($subpage !== '') {
2568 $ns = $this->mTitle
->getNamespace();
2570 $title = Title
::newFromText( $part1, $ns );
2572 if ( !is_null( $title ) ) {
2573 if ( !$title->isExternal() ) {
2574 # Check for excessive inclusion
2575 $dbk = $title->getPrefixedDBkey();
2576 if ( $this->incrementIncludeCount( $dbk ) ) {
2577 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2578 # Capture special page output
2579 $text = SpecialPage
::capturePath( $title );
2580 if ( is_string( $text ) ) {
2585 $this->disableCache();
2588 $articleContent = $this->fetchTemplate( $title );
2589 if ( $articleContent !== false ) {
2591 $text = $articleContent;
2592 $replaceHeadings = true;
2597 # If the title is valid but undisplayable, make a link to it
2598 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2599 $text = '[['.$title->getPrefixedText().']]';
2602 } elseif ( $title->isTrans() ) {
2603 // Interwiki transclusion
2604 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2605 $text = $this->interwikiTransclude( $title, 'render' );
2609 $text = $this->interwikiTransclude( $title, 'raw' );
2610 $replaceHeadings = true;
2615 # Template cache array insertion
2616 # Use the original $piece['title'] not the mangled $part1, so that
2617 # modifiers such as RAW: produce separate cache entries
2619 $this->mTemplates
[$piece['title']] = $text;
2620 $text = $linestart . $text;
2625 # Recursive parsing, escaping and link table handling
2626 # Only for HTML output
2627 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2628 $text = wfEscapeWikiText( $text );
2629 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2631 # Clean up argument array
2632 $assocArgs = array();
2634 foreach( $args as $arg ) {
2635 $eqpos = strpos( $arg, '=' );
2636 if ( $eqpos === false ) {
2637 $assocArgs[$index++
] = $arg;
2639 $name = trim( substr( $arg, 0, $eqpos ) );
2640 $value = trim( substr( $arg, $eqpos+
1 ) );
2641 if ( $value === false ) {
2644 if ( $name !== false ) {
2645 $assocArgs[$name] = $value;
2650 # Add a new element to the templace recursion path
2651 $this->mTemplatePath
[$part1] = 1;
2655 # If there are any <onlyinclude> tags, only include them
2656 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2657 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2659 foreach ($m[1] as $piece)
2662 # Remove <noinclude> sections and <includeonly> tags
2663 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2664 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2666 if( $this->mOutputType
== OT_HTML
) {
2667 # Strip <nowiki>, <pre>, etc.
2668 $text = $this->strip( $text, $this->mStripState
);
2669 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2671 $text = $this->replaceVariables( $text, $assocArgs );
2673 # If the template begins with a table or block-level
2674 # element, it should be treated as beginning a new line.
2675 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2676 $text = "\n" . $text;
2678 } elseif ( !$noargs ) {
2679 # $noparse and !$noargs
2680 # Just replace the arguments, not any double-brace items
2681 # This is used for rendered interwiki transclusion
2682 $text = $this->replaceVariables( $text, $assocArgs, true );
2685 # Prune lower levels off the recursion check path
2686 $this->mTemplatePath
= $lastPathLevel;
2689 wfProfileOut( $fname );
2690 return $piece['text'];
2693 # Replace raw HTML by a placeholder
2694 # Add a blank line preceding, to prevent it from mucking up
2695 # immediately preceding headings
2696 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2698 # replace ==section headers==
2699 # XXX this needs to go away once we have a better parser.
2700 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2701 if( !is_null( $title ) )
2702 $encodedname = base64_encode($title->getPrefixedDBkey());
2704 $encodedname = base64_encode("");
2705 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2706 PREG_SPLIT_DELIM_CAPTURE
);
2709 for( $i = 0; $i < count($m); $i +
= 2 ) {
2711 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2713 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2717 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2718 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2719 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2727 # Prune lower levels off the recursion check path
2728 $this->mTemplatePath
= $lastPathLevel;
2731 wfProfileOut( $fname );
2732 return $piece['text'];
2734 wfProfileOut( $fname );
2740 * Fetch the unparsed text of a template and register a reference to it.
2742 function fetchTemplate( $title ) {
2744 // Loop to fetch the article, with up to 1 redirect
2745 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2746 $rev = Revision
::newFromTitle( $title );
2747 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2751 $text = $rev->getText();
2752 if ( $text === false ) {
2756 $title = Title
::newFromRedirect( $text );
2762 * Transclude an interwiki link.
2764 function interwikiTransclude( $title, $action ) {
2765 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2767 if (!$wgEnableScaryTranscluding)
2768 return wfMsg('scarytranscludedisabled');
2770 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2771 // But we'll handle it generally anyway
2772 if ( $title->getNamespace() ) {
2773 // Use the canonical namespace, which should work anywhere
2774 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2776 $articleName = $title->getDBkey();
2779 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2780 $url .= "?action=$action";
2781 if (strlen($url) > 255)
2782 return wfMsg('scarytranscludetoolong');
2783 return $this->fetchScaryTemplateMaybeFromCache($url);
2786 function fetchScaryTemplateMaybeFromCache($url) {
2787 global $wgTranscludeCacheExpiry;
2788 $dbr =& wfGetDB(DB_SLAVE
);
2789 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2790 array('tc_url' => $url));
2792 $time = $obj->tc_time
;
2793 $text = $obj->tc_contents
;
2794 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2799 $text = wfGetHTTP($url);
2801 return wfMsg('scarytranscludefailed', $url);
2803 $dbw =& wfGetDB(DB_MASTER
);
2804 $dbw->replace('transcache', array('tc_url'), array(
2806 'tc_time' => time(),
2807 'tc_contents' => $text));
2813 * Triple brace replacement -- used for template arguments
2816 function argSubstitution( $matches ) {
2817 $arg = trim( $matches['title'] );
2818 $text = $matches['text'];
2819 $inputArgs = end( $this->mArgStack
);
2821 if ( array_key_exists( $arg, $inputArgs ) ) {
2822 $text = $inputArgs[$arg];
2823 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2824 $text = $matches['parts'][0];
2831 * Returns true if the function is allowed to include this entity
2834 function incrementIncludeCount( $dbk ) {
2835 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2836 $this->mIncludeCount
[$dbk] = 0;
2838 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2846 * This function accomplishes several tasks:
2847 * 1) Auto-number headings if that option is enabled
2848 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2849 * 3) Add a Table of contents on the top for users who have enabled the option
2850 * 4) Auto-anchor headings
2852 * It loops through all headlines, collects the necessary data, then splits up the
2853 * string and re-inserts the newly formatted headlines.
2855 * @param string $text
2856 * @param boolean $isMain
2859 function formatHeadings( $text, $isMain=true ) {
2860 global $wgMaxTocLevel, $wgContLang;
2862 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2864 $forceTocHere = false;
2865 if( !$this->mTitle
->userCanEdit() ) {
2868 $showEditLink = $this->mOptions
->getEditSection();
2871 # Inhibit editsection links if requested in the page
2872 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2873 if( $esw->matchAndRemove( $text ) ) {
2876 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2878 $mw =& MagicWord
::get( MAG_NOTOC
);
2879 if( $mw->matchAndRemove( $text ) ) {
2883 # Get all headlines for numbering them and adding funky stuff like [edit]
2884 # links - this is for later, but we need the number of headlines right now
2885 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2887 # if there are fewer than 4 headlines in the article, do not show TOC
2888 if( $numMatches < 4 ) {
2892 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2893 # override above conditions and always show TOC at that place
2895 $mw =& MagicWord
::get( MAG_TOC
);
2896 if($mw->match( $text ) ) {
2898 $forceTocHere = true;
2900 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2901 # override above conditions and always show TOC above first header
2902 $mw =& MagicWord
::get( MAG_FORCETOC
);
2903 if ($mw->matchAndRemove( $text ) ) {
2908 # Never ever show TOC if no headers
2909 if( $numMatches < 1 ) {
2913 # We need this to perform operations on the HTML
2914 $sk =& $this->mOptions
->getSkin();
2918 $sectionCount = 0; # headlineCount excluding template sections
2920 # Ugh .. the TOC should have neat indentation levels which can be
2921 # passed to the skin functions. These are determined here
2925 $sublevelCount = array();
2926 $levelCount = array();
2933 foreach( $matches[3] as $headline ) {
2935 $templatetitle = '';
2936 $templatesection = 0;
2939 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2941 $templatetitle = base64_decode($mat[1]);
2942 $templatesection = 1 +
(int)base64_decode($mat[2]);
2943 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2947 $prevlevel = $level;
2948 $prevtoclevel = $toclevel;
2950 $level = $matches[1][$headlineCount];
2952 if( $doNumberHeadings ||
$doShowToc ) {
2954 if ( $level > $prevlevel ) {
2955 # Increase TOC level
2957 $sublevelCount[$toclevel] = 0;
2958 $toc .= $sk->tocIndent();
2960 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2961 # Decrease TOC level, find level to jump to
2963 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2964 # Can only go down to level 1
2967 for ($i = $toclevel; $i > 0; $i--) {
2968 if ( $levelCount[$i] == $level ) {
2969 # Found last matching level
2973 elseif ( $levelCount[$i] < $level ) {
2974 # Found first matching level below current level
2981 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2984 # No change in level, end TOC line
2985 $toc .= $sk->tocLineEnd();
2988 $levelCount[$toclevel] = $level;
2990 # count number of headlines for each level
2991 @$sublevelCount[$toclevel]++
;
2993 for( $i = 1; $i <= $toclevel; $i++
) {
2994 if( !empty( $sublevelCount[$i] ) ) {
2998 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3004 # The canonized header is a version of the header text safe to use for links
3005 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3006 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3007 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3009 # Remove link placeholders by the link text.
3010 # <!--LINK number-->
3012 # link text with suffix
3013 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3014 "\$this->mLinkHolders['texts'][\$1]",
3015 $canonized_headline );
3016 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3017 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3018 $canonized_headline );
3021 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3022 $tocline = trim( $canonized_headline );
3023 # Save headline for section edit hint before it's escaped
3024 $headline_hint = trim( $canonized_headline );
3025 $canonized_headline = Sanitizer
::escapeId( $tocline );
3026 $refers[$headlineCount] = $canonized_headline;
3028 # count how many in assoc. array so we can track dupes in anchors
3029 @$refers[$canonized_headline]++
;
3030 $refcount[$headlineCount]=$refers[$canonized_headline];
3032 # Don't number the heading if it is the only one (looks silly)
3033 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3034 # the two are different if the line contains a link
3035 $headline=$numbering . ' ' . $headline;
3038 # Create the anchor for linking from the TOC to the section
3039 $anchor = $canonized_headline;
3040 if($refcount[$headlineCount] > 1 ) {
3041 $anchor .= '_' . $refcount[$headlineCount];
3043 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3044 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3046 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3047 if ( empty( $head[$headlineCount] ) ) {
3048 $head[$headlineCount] = '';
3051 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3053 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3056 # give headline the correct <h#> tag
3057 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3065 $toc .= $sk->tocUnindent( $toclevel - 1 );
3066 $toc = $sk->tocList( $toc );
3069 # split up and insert constructed headlines
3071 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3074 foreach( $blocks as $block ) {
3075 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3076 # This is the [edit] link that appears for the top block of text when
3077 # section editing is enabled
3079 # Disabled because it broke block formatting
3080 # For example, a bullet point in the top line
3081 # $full .= $sk->editSectionLink(0);
3084 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3085 # Top anchor now in skin
3089 if( !empty( $head[$i] ) ) {
3095 $mw =& MagicWord
::get( MAG_TOC
);
3096 return $mw->replace( $toc, $full );
3103 * Return an HTML link for the "ISBN 123456" text
3106 function magicISBN( $text ) {
3107 $fname = 'Parser::magicISBN';
3108 wfProfileIn( $fname );
3110 $a = split( 'ISBN ', ' '.$text );
3111 if ( count ( $a ) < 2 ) {
3112 wfProfileOut( $fname );
3115 $text = substr( array_shift( $a ), 1);
3116 $valid = '0123456789-Xx';
3118 foreach ( $a as $x ) {
3119 $isbn = $blank = '' ;
3120 while ( ' ' == $x{0} ) {
3122 $x = substr( $x, 1 );
3124 if ( $x == '' ) { # blank isbn
3125 $text .= "ISBN $blank";
3128 while ( strstr( $valid, $x{0} ) != false ) {
3130 $x = substr( $x, 1 );
3132 $num = str_replace( '-', '', $isbn );
3133 $num = str_replace( ' ', '', $num );
3134 $num = str_replace( 'x', 'X', $num );
3137 $text .= "ISBN $blank$x";
3139 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3140 $text .= '<a href="' .
3141 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3142 "\" class=\"internal\">ISBN $isbn</a>";
3146 wfProfileOut( $fname );
3151 * Return an HTML link for the "RFC 1234" text
3154 * @param string $text Text to be processed
3155 * @param string $keyword Magic keyword to use (default RFC)
3156 * @param string $urlmsg Interface message to use (default rfcurl)
3159 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3161 $valid = '0123456789';
3164 $a = split( $keyword, ' '.$text );
3165 if ( count ( $a ) < 2 ) {
3168 $text = substr( array_shift( $a ), 1);
3170 /* Check if keyword is preceed by [[.
3171 * This test is made here cause of the array_shift above
3172 * that prevent the test to be done in the foreach.
3174 if ( substr( $text, -2 ) == '[[' ) {
3178 foreach ( $a as $x ) {
3179 /* token might be empty if we have RFC RFC 1234 */
3187 /** remove and save whitespaces in $blank */
3188 while ( $x{0} == ' ' ) {
3190 $x = substr( $x, 1 );
3193 /** remove and save the rfc number in $id */
3194 while ( strstr( $valid, $x{0} ) != false ) {
3196 $x = substr( $x, 1 );
3200 /* call back stripped spaces*/
3201 $text .= $keyword.$blank.$x;
3202 } elseif( $internal ) {
3204 $text .= $keyword.$id.$x;
3206 /* build the external link*/
3207 $url = wfMsg( $urlmsg, $id);
3208 $sk =& $this->mOptions
->getSkin();
3209 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3210 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3213 /* Check if the next RFC keyword is preceed by [[ */
3214 $internal = ( substr($x,-2) == '[[' );
3220 * Transform wiki markup when saving a page by doing \r\n -> \n
3221 * conversion, substitting signatures, {{subst:}} templates, etc.
3223 * @param string $text the text to transform
3224 * @param Title &$title the Title object for the current article
3225 * @param User &$user the User object describing the current user
3226 * @param ParserOptions $options parsing options
3227 * @param bool $clearState whether to clear the parser state first
3228 * @return string the altered wiki markup
3231 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3232 $this->mOptions
= $options;
3233 $this->mTitle
=& $title;
3234 $this->mOutputType
= OT_WIKI
;
3236 if ( $clearState ) {
3237 $this->clearState();
3240 $stripState = false;
3244 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3245 $text = $this->strip( $text, $stripState, true );
3246 $text = $this->pstPass2( $text, $user );
3247 $text = $this->unstrip( $text, $stripState );
3248 $text = $this->unstripNoWiki( $text, $stripState );
3253 * Pre-save transform helper function
3256 function pstPass2( $text, &$user ) {
3257 global $wgContLang, $wgLocaltimezone;
3259 /* Note: This is the timestamp saved as hardcoded wikitext to
3260 * the database, we use $wgContLang here in order to give
3261 * everyone the same signiture and use the default one rather
3262 * than the one selected in each users preferences.
3264 if ( isset( $wgLocaltimezone ) ) {
3265 $oldtz = getenv( 'TZ' );
3266 putenv( 'TZ='.$wgLocaltimezone );
3268 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3269 ' (' . date( 'T' ) . ')';
3270 if ( isset( $wgLocaltimezone ) ) {
3271 putenv( 'TZ='.$oldtz );
3274 # Variable replacement
3275 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3276 $text = $this->replaceVariables( $text );
3279 $sigText = $this->getUserSig( $user );
3280 $text = strtr( $text, array(
3282 '~~~~' => "$sigText $d",
3286 # Context links: [[|name]] and [[name (context)|]]
3288 global $wgLegalTitleChars;
3289 $tc = "[$wgLegalTitleChars]";
3290 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3292 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3293 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3295 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3296 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3297 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3298 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3300 $t = $this->mTitle
->getText();
3301 if ( preg_match( $conpat, $t, $m ) ) {
3304 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3305 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3306 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3308 if ( '' == $context ) {
3309 $text = preg_replace( $p2, '[[\\1]]', $text );
3311 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3314 # Trim trailing whitespace
3315 # MAG_END (__END__) tag allows for trailing
3316 # whitespace to be deliberately included
3317 $text = rtrim( $text );
3318 $mw =& MagicWord
::get( MAG_END
);
3319 $mw->matchAndRemove( $text );
3325 * Fetch the user's signature text, if any, and normalize to
3326 * validated, ready-to-insert wikitext.
3332 function getUserSig( &$user ) {
3335 $username = $user->getName();
3336 $nickname = $user->getOption( 'nickname' );
3337 $nickname = $nickname === '' ?
$username : $nickname;
3339 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3340 # Sig. might contain markup; validate this
3341 if( $this->validateSig( $nickname ) !== false ) {
3342 # Validated; clean up (if needed) and return it
3343 return( $this->cleanSig( $nickname ) );
3345 # Failed to validate; fall back to the default
3346 $nickname = $username;
3347 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3351 # If we're still here, make it a link to the user page
3352 $userpage = $user->getUserPage();
3353 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3357 * Check that the user's signature contains no bad XML
3359 * @param string $text
3360 * @return mixed An expanded string, or false if invalid.
3362 function validateSig( $text ) {
3363 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3367 * Clean up signature text
3369 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3370 * 2) Substitute all transclusions
3372 * @param string $text
3373 * @return string Signature text
3375 function cleanSig( $text ) {
3376 $substWord = MagicWord
::get( MAG_SUBST
);
3377 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3378 $substText = '{{' . $substWord->getSynonym( 0 );
3380 $text = preg_replace( $substRegex, $substText, $text );
3381 $text = preg_replace( '/~{3,5}/', '', $text );
3382 $text = $this->replaceVariables( $text );
3388 * Set up some variables which are usually set up in parse()
3389 * so that an external function can call some class members with confidence
3392 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3393 $this->mTitle
=& $title;
3394 $this->mOptions
= $options;
3395 $this->mOutputType
= $outputType;
3396 if ( $clearState ) {
3397 $this->clearState();
3402 * Transform a MediaWiki message by replacing magic variables.
3404 * @param string $text the text to transform
3405 * @param ParserOptions $options options
3406 * @return string the text with variables substituted
3409 function transformMsg( $text, $options ) {
3411 static $executing = false;
3413 $fname = "Parser::transformMsg";
3415 # Guard against infinite recursion
3421 wfProfileIn($fname);
3423 $this->mTitle
= $wgTitle;
3424 $this->mOptions
= $options;
3425 $this->mOutputType
= OT_MSG
;
3426 $this->clearState();
3427 $text = $this->replaceVariables( $text );
3430 wfProfileOut($fname);
3435 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3436 * The callback should have the following form:
3437 * function myParserHook( $text, $params, &$parser ) { ... }
3439 * Transform and return $text. Use $parser for any required context, e.g. use
3440 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3444 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3445 * @param mixed $callback The callback function (and object) to use for the tag
3447 * @return The old value of the mTagHooks array associated with the hook
3449 function setHook( $tag, $callback ) {
3450 $oldVal = @$this->mTagHooks
[$tag];
3451 $this->mTagHooks
[$tag] = $callback;
3457 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3458 * Placeholders created in Skin::makeLinkObj()
3459 * Returns an array of links found, indexed by PDBK:
3463 * $options is a bit field, RLH_FOR_UPDATE to select for update
3465 function replaceLinkHolders( &$text, $options = 0 ) {
3467 global $wgOutputReplace;
3469 $fname = 'Parser::replaceLinkHolders';
3470 wfProfileIn( $fname );
3474 $sk =& $this->mOptions
->getSkin();
3475 $linkCache =& LinkCache
::singleton();
3477 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3478 wfProfileIn( $fname.'-check' );
3479 $dbr =& wfGetDB( DB_SLAVE
);
3480 $page = $dbr->tableName( 'page' );
3481 $threshold = $wgUser->getOption('stubthreshold');
3484 asort( $this->mLinkHolders
['namespaces'] );
3488 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3490 $title = $this->mLinkHolders
['titles'][$key];
3492 # Skip invalid entries.
3493 # Result will be ugly, but prevents crash.
3494 if ( is_null( $title ) ) {
3497 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3499 # Check if it's a static known link, e.g. interwiki
3500 if ( $title->isAlwaysKnown() ) {
3501 $colours[$pdbk] = 1;
3502 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3503 $colours[$pdbk] = 1;
3504 $this->mOutput
->addLink( $title, $id );
3505 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3506 $colours[$pdbk] = 0;
3508 # Not in the link cache, add it to the query
3509 if ( !isset( $current ) ) {
3511 $query = "SELECT page_id, page_namespace, page_title";
3512 if ( $threshold > 0 ) {
3513 $query .= ', page_len, page_is_redirect';
3515 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3516 } elseif ( $current != $ns ) {
3518 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3523 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3528 if ( $options & RLH_FOR_UPDATE
) {
3529 $query .= ' FOR UPDATE';
3532 $res = $dbr->query( $query, $fname );
3534 # Fetch data and form into an associative array
3535 # non-existent = broken
3538 while ( $s = $dbr->fetchObject($res) ) {
3539 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3540 $pdbk = $title->getPrefixedDBkey();
3541 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3542 $this->mOutput
->addLink( $title, $s->page_id
);
3544 if ( $threshold > 0 ) {
3545 $size = $s->page_len
;
3546 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3547 $colours[$pdbk] = 1;
3549 $colours[$pdbk] = 2;
3552 $colours[$pdbk] = 1;
3556 wfProfileOut( $fname.'-check' );
3558 # Construct search and replace arrays
3559 wfProfileIn( $fname.'-construct' );
3560 $wgOutputReplace = array();
3561 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3562 $pdbk = $pdbks[$key];
3563 $searchkey = "<!--LINK $key-->";
3564 $title = $this->mLinkHolders
['titles'][$key];
3565 if ( empty( $colours[$pdbk] ) ) {
3566 $linkCache->addBadLinkObj( $title );
3567 $colours[$pdbk] = 0;
3568 $this->mOutput
->addLink( $title, 0 );
3569 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3570 $this->mLinkHolders
['texts'][$key],
3571 $this->mLinkHolders
['queries'][$key] );
3572 } elseif ( $colours[$pdbk] == 1 ) {
3573 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3574 $this->mLinkHolders
['texts'][$key],
3575 $this->mLinkHolders
['queries'][$key] );
3576 } elseif ( $colours[$pdbk] == 2 ) {
3577 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3578 $this->mLinkHolders
['texts'][$key],
3579 $this->mLinkHolders
['queries'][$key] );
3582 wfProfileOut( $fname.'-construct' );
3585 wfProfileIn( $fname.'-replace' );
3587 $text = preg_replace_callback(
3588 '/(<!--LINK .*?-->)/',
3589 "wfOutputReplaceMatches",
3592 wfProfileOut( $fname.'-replace' );
3595 # Now process interwiki link holders
3596 # This is quite a bit simpler than internal links
3597 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3598 wfProfileIn( $fname.'-interwiki' );
3599 # Make interwiki link HTML
3600 $wgOutputReplace = array();
3601 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3602 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3603 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3606 $text = preg_replace_callback(
3607 '/<!--IWLINK (.*?)-->/',
3608 "wfOutputReplaceMatches",
3610 wfProfileOut( $fname.'-interwiki' );
3613 wfProfileOut( $fname );
3618 * Replace <!--LINK--> link placeholders with plain text of links
3619 * (not HTML-formatted).
3620 * @param string $text
3623 function replaceLinkHoldersText( $text ) {
3625 global $wgOutputReplace;
3627 $fname = 'Parser::replaceLinkHoldersText';
3628 wfProfileIn( $fname );
3630 $text = preg_replace_callback(
3631 '/<!--(LINK|IWLINK) (.*?)-->/',
3632 array( &$this, 'replaceLinkHoldersTextCallback' ),
3635 wfProfileOut( $fname );
3640 * @param array $matches
3644 function replaceLinkHoldersTextCallback( $matches ) {
3645 $type = $matches[1];
3647 if( $type == 'LINK' ) {
3648 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3649 return $this->mLinkHolders
['texts'][$key];
3651 } elseif( $type == 'IWLINK' ) {
3652 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3653 return $this->mInterwikiLinkHolders
['texts'][$key];
3660 * Renders an image gallery from a text with one line per image.
3661 * text labels may be given by using |-style alternative text. E.g.
3662 * Image:one.jpg|The number "1"
3663 * Image:tree.jpg|A tree
3664 * given as text will return the HTML of a gallery with two images,
3665 * labeled 'The number "1"' and
3668 function renderImageGallery( $text ) {
3670 $parserOptions = new ParserOptions
;
3671 $localParser = new Parser();
3673 $ig = new ImageGallery();
3674 $ig->setShowBytes( false );
3675 $ig->setShowFilename( false );
3676 $lines = explode( "\n", $text );
3678 foreach ( $lines as $line ) {
3679 # match lines like these:
3680 # Image:someimage.jpg|This is some image
3681 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3683 if ( count( $matches ) == 0 ) {
3686 $nt =& Title
::newFromText( $matches[1] );
3687 if( is_null( $nt ) ) {
3688 # Bogus title. Ignore these so we don't bomb out later.
3691 if ( isset( $matches[3] ) ) {
3692 $label = $matches[3];
3697 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3698 $html = $pout->getText();
3700 $ig->add( new Image( $nt ), $html );
3701 $this->mOutput
->addImage( $nt->getDBkey() );
3703 return $ig->toHTML();
3707 * Parse image options text and use it to make an image
3709 function makeImage( &$nt, $options ) {
3710 global $wgContLang, $wgUseImageResize, $wgUser;
3714 # Check if the options text is of the form "options|alt text"
3716 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3717 # * left no resizing, just left align. label is used for alt= only
3718 # * right same, but right aligned
3719 # * none same, but not aligned
3720 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3721 # * center center the image
3722 # * framed Keep original image size, no magnify-button.
3724 $part = explode( '|', $options);
3726 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3727 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3728 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3729 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3730 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3731 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3732 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3733 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3736 $width = $height = $framed = $thumb = false;
3737 $manual_thumb = '' ;
3739 foreach( $part as $key => $val ) {
3740 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3742 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3743 # use manually specified thumbnail
3745 $manual_thumb = $match;
3746 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3747 # remember to set an alignment, don't render immediately
3749 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3750 # remember to set an alignment, don't render immediately
3752 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3753 # remember to set an alignment, don't render immediately
3755 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3756 # remember to set an alignment, don't render immediately
3758 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3759 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3760 # $match is the image width in pixels
3761 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3762 $width = intval( $m[1] );
3763 $height = intval( $m[2] );
3765 $width = intval($match);
3767 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3773 # Strip bad stuff out of the alt text
3774 $alt = $this->replaceLinkHoldersText( $caption );
3775 $alt = Sanitizer
::stripAllTags( $alt );
3777 # Linker does the rest
3778 $sk =& $this->mOptions
->getSkin();
3779 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3783 * Set a flag in the output object indicating that the content is dynamic and
3784 * shouldn't be cached.
3786 function disableCache() {
3787 $this->mOutput
->mCacheTime
= -1;
3791 * Callback from the Sanitizer for expanding items found in HTML attribute
3792 * values, so they can be safely tested and escaped.
3793 * @param string $text
3794 * @param array $args
3798 function attributeStripCallback( &$text, $args ) {
3799 $text = $this->replaceVariables( $text, $args );
3800 $text = $this->unstripForHTML( $text );
3804 function unstripForHTML( $text ) {
3805 $text = $this->unstrip( $text, $this->mStripState
);
3806 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3814 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3815 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3816 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3822 function getTags() { return array_keys( $this->mTagHooks
); }
3828 * @package MediaWiki
3832 var $mText, # The output text
3833 $mLanguageLinks, # List of the full text of language links, in the order they appear
3834 $mCategories, # Map of category names to sort keys
3835 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3836 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3837 $mVersion, # Compatibility check
3838 $mTitleText, # title text of the chosen language variant
3839 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3840 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3841 $mImages, # DB keys of the images used, in the array key only
3842 $mExternalLinks; # External link URLs, in the key only
3844 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3845 $containsOldMagic = false, $titletext = '' )
3847 $this->mText
= $text;
3848 $this->mLanguageLinks
= $languageLinks;
3849 $this->mCategories
= $categoryLinks;
3850 $this->mContainsOldMagic
= $containsOldMagic;
3851 $this->mCacheTime
= '';
3852 $this->mVersion
= MW_PARSER_VERSION
;
3853 $this->mTitleText
= $titletext;
3854 $this->mLinks
= array();
3855 $this->mTemplates
= array();
3856 $this->mImages
= array();
3857 $this->mExternalLinks
= array();
3860 function getText() { return $this->mText
; }
3861 function getLanguageLinks() { return $this->mLanguageLinks
; }
3862 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3863 function &getCategories() { return $this->mCategories
; }
3864 function getCacheTime() { return $this->mCacheTime
; }
3865 function getTitleText() { return $this->mTitleText
; }
3866 function &getLinks() { return $this->mLinks
; }
3867 function &getTemplates() { return $this->mTemplates
; }
3868 function &getImages() { return $this->mImages
; }
3869 function &getExternalLinks() { return $this->mExternalLinks
; }
3871 function containsOldMagic() { return $this->mContainsOldMagic
; }
3872 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3873 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3874 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3875 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3876 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3877 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3879 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3880 function addImage( $name ) { $this->mImages
[$name] = 1; }
3881 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3882 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3884 function addLink( $title, $id ) {
3885 $ns = $title->getNamespace();
3886 $dbk = $title->getDBkey();
3887 if ( !isset( $this->mLinks
[$ns] ) ) {
3888 $this->mLinks
[$ns] = array();
3890 $this->mLinks
[$ns][$dbk] = $id;
3893 function addTemplate( $title, $id ) {
3894 $ns = $title->getNamespace();
3895 $dbk = $title->getDBkey();
3896 if ( !isset( $this->mTemplates
[$ns] ) ) {
3897 $this->mTemplates
[$ns] = array();
3899 $this->mTemplates
[$ns][$dbk] = $id;
3906 function merge( $other ) {
3907 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3908 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3909 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3913 * Return true if this cached output object predates the global or
3914 * per-article cache invalidation timestamps, or if it comes from
3915 * an incompatible older version.
3917 * @param string $touched the affected article's last touched timestamp
3921 function expired( $touched ) {
3922 global $wgCacheEpoch;
3923 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3924 $this->getCacheTime() < $touched ||
3925 $this->getCacheTime() <= $wgCacheEpoch ||
3926 !isset( $this->mVersion
) ||
3927 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3932 * Set options of the Parser
3934 * @package MediaWiki
3938 # All variables are private
3939 var $mUseTeX; # Use texvc to expand <math> tags
3940 var $mUseDynamicDates; # Use DateFormatter to format dates
3941 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3942 var $mAllowExternalImages; # Allow external images inline
3943 var $mAllowExternalImagesFrom; # If not, any exception?
3944 var $mSkin; # Reference to the preferred skin
3945 var $mDateFormat; # Date format index
3946 var $mEditSection; # Create "edit section" links
3947 var $mNumberHeadings; # Automatically number headings
3948 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3949 var $mTidy; # Ask for tidy cleanup
3951 function getUseTeX() { return $this->mUseTeX
; }
3952 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3953 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3954 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3955 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3956 function &getSkin() { return $this->mSkin
; }
3957 function getDateFormat() { return $this->mDateFormat
; }
3958 function getEditSection() { return $this->mEditSection
; }
3959 function getNumberHeadings() { return $this->mNumberHeadings
; }
3960 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3961 function getTidy() { return $this->mTidy
; }
3963 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3964 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3965 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3966 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3967 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3968 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3969 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3970 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3971 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3972 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3973 function setSkin( &$x ) { $this->mSkin
=& $x; }
3975 function ParserOptions() {
3977 $this->initialiseFromUser( $wgUser );
3981 * Get parser options
3984 function newFromUser( &$user ) {
3985 $popts = new ParserOptions
;
3986 $popts->initialiseFromUser( $user );
3990 /** Get user options */
3991 function initialiseFromUser( &$userInput ) {
3992 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3993 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3994 $fname = 'ParserOptions::initialiseFromUser';
3995 wfProfileIn( $fname );
3996 if ( !$userInput ) {
3998 $user->setLoaded( true );
4000 $user =& $userInput;
4003 $this->mUseTeX
= $wgUseTeX;
4004 $this->mUseDynamicDates
= $wgUseDynamicDates;
4005 $this->mInterwikiMagic
= $wgInterwikiMagic;
4006 $this->mAllowExternalImages
= $wgAllowExternalImages;
4007 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4008 wfProfileIn( $fname.'-skin' );
4009 $this->mSkin
=& $user->getSkin();
4010 wfProfileOut( $fname.'-skin' );
4011 $this->mDateFormat
= $user->getOption( 'date' );
4012 $this->mEditSection
= true;
4013 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4014 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4015 $this->mTidy
= false;
4016 wfProfileOut( $fname );
4021 * Callback function used by Parser::replaceLinkHolders()
4022 * to substitute link placeholders.
4024 function &wfOutputReplaceMatches( $matches ) {
4025 global $wgOutputReplace;
4026 return $wgOutputReplace[$matches[1]];
4030 * Return the total number of articles
4032 function wfNumberOfArticles() {
4033 global $wgNumberOfArticles;
4036 return $wgNumberOfArticles;
4040 * Return the number of files
4042 function wfNumberOfFiles() {
4043 $fname = 'Parser::wfNumberOfFiles';
4045 wfProfileIn( $fname );
4046 $dbr =& wfGetDB( DB_SLAVE
);
4047 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4048 wfProfileOut( $fname );
4054 * Get various statistics from the database
4057 function wfLoadSiteStats() {
4058 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4059 $fname = 'wfLoadSiteStats';
4061 if ( -1 != $wgNumberOfArticles ) return;
4062 $dbr =& wfGetDB( DB_SLAVE
);
4063 $s = $dbr->selectRow( 'site_stats',
4064 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4065 array( 'ss_row_id' => 1 ), $fname
4068 if ( $s === false ) {
4071 $wgTotalViews = $s->ss_total_views
;
4072 $wgTotalEdits = $s->ss_total_edits
;
4073 $wgNumberOfArticles = $s->ss_good_articles
;
4079 * Basically replacing " > and < with HTML entities ( ", >, <)
4081 * @param string $in Text that might contain HTML tags
4082 * @return string Escaped string
4084 function wfEscapeHTMLTagsOnly( $in ) {
4086 array( '"', '>', '<' ),
4087 array( '"', '>', '<' ),